package com.usian.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.feign.BehaviorFeign;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dto.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.service.ApUserSearchService;
import com.usian.service.SearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;
    @Autowired
    private BehaviorFeign behaviorFeign;


    @Override
    public ResponseResult search(UserSearchDto dto) {

        try{
            //1:校验参数
            if(dto==null){
                return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            //当用户搜索是触发线程池异步调用save记录的方法
            ApUser apUser = AppThreadLocalUtils.getUser();
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }
            com.usian.model.behavior.pojos.ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserId(apUser.getId(), null);
            if(behaviorEntry==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            apUserSearchService.insert(behaviorEntry.getId(),dto.getSearchWords());


            //2:调用查询方法 search（）
            SearchRequest searchRequest =new SearchRequest("app_info_article");

            SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();

            //4: searchSourceBuilder 对象  条件构造器

            // select * from table  where (title=? or content=?) and publishTime< ? order by xxxxx limit ?,?
            //
            //        publishTime desc

            BoolQueryBuilder boolQueryBuilder =new BoolQueryBuilder();

            QueryStringQueryBuilder stringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title").field("content").defaultOperator(Operator.OR);

            boolQueryBuilder.must(stringQueryBuilder);

            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
            boolQueryBuilder.filter(rangeQueryBuilder);


            //排序
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);
            //分页
            searchSourceBuilder.from(dto.getPageNum());
            searchSourceBuilder.size(dto.getPageSize());

            //3: searchRequest 对象  source（）
            searchRequest.source(searchSourceBuilder);

            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //5:解析查询结果
            SearchHit[] hits = response.getHits().getHits();

            List<Map> articleList = new ArrayList<>();

            for(SearchHit searchHit : hits){
                //第一条数据 且转换为string字符串
                String asString = searchHit.getSourceAsString();

                //fastjson 转一下
                Map map = JSON.parseObject(asString, Map.class);
                articleList.add(map);
            }


            //6:转成map集合封装到ResponseResult返回
            return ResponseResult.okResult(articleList);

        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }finally {
            System.out.println("1111111");
        }
    }
}
